<?php
/**
 * Created by PhpStorm.
 * User: chen
 * Date: 2016/4/6
 * Time: 12:51
 */
namespace liketry\controllers;

use common\models\OrderGoodsHistory;
use services\models\Comments;
use services\models\CommentsRelation;
use services\models\Goods;
use services\models\GoodsDetail;
use services\models\OrderGoods;
use services\models\OrderInfo;
use services\models\OrderInfoHistory;
use services\models\Product;
use services\models\ProhibitedWords;
use Yii;
use yii\data\Pagination;


class CommentsController extends CustomController
{

/*    public function  init(){
        Yii::$app->request->enableCsrfValidation = false;
    }*/
    /*
     * 发表评论view
     * */
    public function actionIndex()
    {
        if(!$this->isLogin()){
            return $this->redirect($this->login_url);
        }
        /*
         * 发表评论，get数据应包含:order_info_id,goods_id
         * */
        $order_id = Yii::$app->request->get('order_info_id');
        $goods_id = Yii::$app->request->get('goods_id');

        $commentsModel = new Comments();
        $orderInfo = OrderGoods::find()->where(['order_info_id' => $order_id, 'bestry_uid' => $this->bestry_uid, 'goods_id' => $goods_id])->one();

        if(empty($orderInfo)){
            $orderInfo = OrderGoodsHistory::find()->where(['order_info_id' => $order_id, 'bestry_uid' => $this->bestry_uid, 'goods_id' => $goods_id])->one();
            if(empty($orderInfo)){
                return $this->redirect(['order-details/order-detail', 'order_info_id'=>$order_id]);
            }

        } 

        //取支付金额数据
        //$payInfo = OrderInfo::find()->select('order_amount,try_coin')->where(['order_info_id' => $order_id])->one()->toArray();

        //取商品名称
        $goodsInfo = GoodsDetail::findByGoodsId($orderInfo['goods_id'],'goods_name');


        //取图片地址
        //判断是喜试还是优选   //TODO 喜试和优选区别
        $isOrNoLiketry   =Yii::$app->redis_goods->sismember('oldLiketryOrderGoodsId',$order_id.'_'.$goods_id.'_'.$orderInfo['product_id']);
        //取商品详情 如果是喜试的商品则加goods_id+ 2000万
        if($isOrNoLiketry)
            $img  = Goods::findByGoodsIdFromRedis($goods_id+20000000, array('bigpic'));
        else
            $img  = Goods::findByGoodsIdFromRedis($goods_id, array('bigpic'));


        //$img = Goods::findByGoodsIdFromRedis($goods_id, array('bigpic'));
        $image = Yii::$app->params['goods_image_url'].str_replace('./upload', 'upload', $img['bigpic']);

        $dataProvider = array(
            'order_id'  => $order_id,
            'goods_id'  => $orderInfo['goods_id'],
            'product_id'    => $orderInfo['product_id'],
            'goods_name'    => $goodsInfo['goods_name'],
            'order_amount'  => $orderInfo['buy_price'],
            'try_coin'  => $orderInfo['try_coin'],
            'img'   => $image
        );

        return $this->render('comments_add', [
            'model' => $commentsModel,
            'data'  => $dataProvider,
        ]);

    }

    /*
     * 发表评论save
     * */
    public function actionCreate()
    {
        /*
         * 发表评论，post数据应包含：order_id,goods_id,level,content,img
         * */
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $model = new Comments();
        $order_id = intval(Yii::$app->request->post('order_id'));
        $goods_id = intval(Yii::$app->request->post('goods_id'));
        $level = intval(Yii::$app->request->post('level'));
        $content = Yii::$app->request->post('content');
        $model->img = Yii::$app->request->post('img');
        $model->create_time = date("Y-m-d H:i:s");
        $bestry_uid = $this->bestry_uid;
        //$bestry_uid = 1;

        if($bestry_uid <= 0){
            return ['flag' => false, 'msg' => '请先绑定用户！'];
        }

        if($order_id < 1 || mb_strlen($content, 'utf-8') < 10 || $level < 1 ||  $level > 5){
            return ['flag'=>false, 'msg'=>'参数错误！'];
        }
        $result = OrderGoods::find()->where(['order_info_id'=>$order_id, 'bestry_uid'=>$bestry_uid, 'goods_id' => $goods_id])->one();

        if(empty($result)){
            return ['flag'=>false, 'msg'=>'信息不匹配！'];
        }
        if(1 == $result->commented){
            return ['flag' => false, 'msg' => '商品已评价！'];
        }

        $goods_id = $result->goods_id;
        $product_id = $result->product_id;

        $orderInfo = OrderInfo::find()->select('status,pay_status')->where(['order_info_id' => $order_id])->one()->toArray();

        if($orderInfo['status'] != OrderInfo::$STATUS_ORDER_OK || $orderInfo['pay_status'] != OrderInfo::$STATUS_PAYED){
            return ['flag' => false, 'msg' => '订单未支付或者不是【订单完成】状态，无法评价！'];
        }
        $commentInfo = CommentsRelation::find()->where(['order_id' => $order_id, 'goods_id' => $goods_id, 'product_id' => $product_id])->one();
        if(!empty($commentInfo)){
            return ['flag' => false, 'msg' => '商品已评价！'];
        }

        $prohibit = new ProhibitedWords();
       $test = $prohibit->filterForComments($content);//判断是否有敏感词
        if(!$test['flag']){
             return ['flag' => false, 'msg' => '您输入的“'.$test['msg'].'”可能涉及敏感词汇，请重新输入'];
         }

        $try = Product::findByProductId($product_id);
        $is_try = isset($try['type']) && $try['type'] == 1 ? 1 : 0;//是否是试用商品
        $model->content = $content;
        if($model->load(Yii::$app->request->post(),'') && $model->save()){

            $relationArray = array(
                'comment_id'=> $model->comment_id,
                'order_id'  => $order_id,
                'goods_id'  => $goods_id,
                'product_id'=> $product_id,
                'bestry_uid'=> $bestry_uid,
                'level'     => $level,
                'create_time'   => date("Y-m-d H:i:s"),
                'is_try'    => $is_try,/*是否是试用商品*/
                'is_reply'  => 0,
                'reply_id'  => 0,
                'is_show'   => 1,/*默认展示*/
                'status'    => 0,/*1精华 0普通 2不通过*/
            );
            $relationModel = new CommentsRelation($relationArray);
            if($relationModel->save()){//评论发表成功后，保存评论信息至redis、加试豆奖励、修改订单商品评论状态

                $model->saveCommentToRedis($bestry_uid, \yii\helpers\ArrayHelper::toArray($model), $relationArray);
                $model->addMemberScore($bestry_uid);
                $result->commented = OrderGoods::$_COMMENTED_HAVE;
                $result->save();
                return ['flag'=>true, 'msg'=>'发表评论成功！'];
            }
        }

        return ['flag'=>false, 'msg'=>'发表评论失败，请重试！'];
    }


    public function actionShow(){

        if(!$this->isLogin()){
            return $this->redirect($this->login_url);
        }
        $bestry_uid = $this->bestry_uid;
        $type = 0;
        $is_perfect = Yii::$app->request->get('is_perfect') == 1 ? 1:0;
        $is_reply   = Yii::$app->request->get('is_reply') == 1 ? 1:0;
        $page_no   = intval(Yii::$app->request->get('page'))>0?intval(Yii::$app->request->get('page')):1;

        $condition = array(
            'is_perfect'    => $is_perfect,
            'is_reply'      => $is_reply,
        );
        if($is_perfect){
            $type = 1;
        }
        elseif($is_reply){
            $type = 2;
        }

        $page_size = 10;//每页显示条数
        $model = new CommentsRelation();
        $num = $model->getOwnCommentsNumberFromRedis($bestry_uid);//评论总数
        $ids = $model->getOwnCommentsIds($bestry_uid, $condition);//评论ID列表

        $idArr = array_chunk($ids, $page_size, true);//按每页显示条数分割ids
        $page_count = count($ids);//总数
        $info = '';
        if(!empty($idArr)){
            $c_ids = $idArr[$page_no-1];
            $info = $model->getOwnCommentsFromRedis($c_ids);
        }

        //var_dump($info);

        $page = new Pagination(['totalCount' => $page_count, 'pageSize' => $page_size]);

        return $this->render('comments_list', [
            'data' =>  $info,
            'page'   =>  $page,
            'type'  => $type,
            'num'   => $num
        ]);

    }


}